
kuruTouch = nil
g_modelContext = nil
g_material = nil
g_frameBuffer = nil
g_frameBufferSampler = nil
-- g_dpFilterNode = nil --切割后的图片
-- passFilterNode = nil  --显示切割场景图片
-- originNode = nil  --原图片
resultNode = nil --切割后的图片
originNodes = {} --初始状态node
wxNodes = {} --微信相关的node
avrtPhotos = {} --头像
g_count = 6 --微信消息数量
messagetotolsamplers = {} --微信消息sampler
isPhotoTake = false --是否拍照了
isAniStart = false --是否开始了动画
g_speed = 1.0 --缩放速度
totalElapsedTime = 0

function initialize(scene)
  local kuruEngineInstance = KuruEngine.getInstance()
  kuruTouch = KuruTouchExtension.cast(kuruEngineInstance:getExtension('KuruTouch')) --触摸操作
  kuruTouch:getTouchDownEvent():addEventHandler(onTouchDown)

  eventExtension = KuruEventExtension.cast(KuruEngine.getInstance():getExtension("KuruEvent"))
  eventExtension:getSimpleEvent():addEventHandler(onSimpleEvent)

  soundExtension = KuruSoundExtension.cast(KuruEngine.getInstance():getExtension("KuruSound"))
  g_sound = soundExtension:loadEx(BASE_DIRECTORY..("aidai.mp3"))
  g_sound:stop()
  createOriginNode(scene)
  createWechat(scene)
end
function createOriginNode(scene)
  local originNode = getCurrentShot(scene,0.7) --源图片
  originNodes[#originNodes] = originNode
  local width= math.floor(scene:getResolution().x*0.7)
  local height=math.floor(scene:getResolution().y*0.7) --保存截图
  g_frameBuffer = FrameBuffer.create("TEMP_STORED_FB_" .. 1, width, height, TextureFormat.RGBA)
  g_frameBufferSampler = TextureSampler.createWithTexture(g_frameBuffer:getRenderTarget(0):getTexture())
  g_frameBufferSampler:setWrapMode(TextureWrap.CLAMP, TextureWrap.CLAMP)
  g_modelContext = createFullscreenQuadMode()
  local g_dpFilterNode = addNodeAndRelease(scene,KuruShaderFilterNode.createWithFragmentShaderFile(BASE_DIRECTORY.."display.frag",true))
  g_dpFilterNode:getMaterial():getParameter("photoImg"):setSampler(originNode:getSampler())
  originNodes[#originNodes] = g_dpFilterNode
  resultNode = getCurrentShot(scene,0.7) --获得切割后的图片
  originNodes[#originNodes] = resultNode
  local passFilterNode = addNodeAndRelease(scene,KuruShaderFilterNode.createWithFragmentShaderFile(BASE_DIRECTORY.."pass.frag",true))
  passFilterNode:getMaterial():getParameter("photoImg"):setSampler(originNode:getSampler())
  originNodes[#originNodes] = passFilterNode
  local originbgNode = addNodeAndRelease(scene, KuruFloatingImageNode.create(BASE_DIRECTORY .. "b_zf.png", -1.0, -1, 2, 2, BlendMode.None))
  originNodes[#originNodes] = originbgNode

end
function createWechat(scene)
  local topHeight = 0.2 --x从-0.95开始
  local middleHeight = 0.9
  local offsetLeft = 0.359
   local bgnode = KuruFloatingImageNode.createFromSampler(g_frameBufferSampler,-1.0+offsetLeft,-1+middleHeight+0.1,2-2*offsetLeft+0.025,2-middleHeight-topHeight-0.2,BlendMode.None)
   wxNodes[#wxNodes+1] = bgnode
   bgnode:setEnabled(false)
   addNodeAndRelease(scene,bgnode)
  
  for i=1,g_count do
    local tempsampler = nil
    if i==1 then
      tempsampler = getStickerSampler("b_one.png",10)
    elseif i==2 then
      tempsampler = getStickerSampler("b_two.png",10)
    elseif i==3 then
      tempsampler = getStickerSampler("b_three.png",10)
    elseif i==4 then
      tempsampler = getStickerSampler("b_four.png",10)
    elseif i==5 then
      tempsampler = getStickerSampler("b_five.png",10)
    elseif i==6 then
      tempsampler = getStickerSampler("b_zero.png",10)
    end
    messagetotolsamplers[i] = tempsampler
  end
  middleSampler = getStickerSampler("b_five.png",10)
  local middlenode = KuruFloatingImageNode.createFromSampler(middleSampler,-1.0,-1+middleHeight+0.0,2,2-middleHeight-topHeight+0.15,BlendMode.None)
  wxNodes[#wxNodes+1] = middlenode
  middlenode:setEnabled(false)
  addNodeAndRelease(scene,middlenode)  -- 1+0.1-topHeight-0.2
  local marginY = 0.0
  for i=1,g_count-1 do
    local avatfNode = nil
    if i==1 then
      avatfNode = KuruFloatingImageNode.createFromSampler(g_frameBufferSampler,1.0-0.30,0.9-topHeight-0.22*0.5625,0.230,0.22*0.5625,BlendMode.None)
      addNodeAndRelease(scene,avatfNode)
    elseif i==2 then
      marginY = 0.02
      avatfNode = KuruFloatingImageNode.createFromSampler(g_frameBufferSampler,1.0-0.30,0.9-topHeight-0.22*0.5625*2-marginY,0.230,0.22*0.5625,BlendMode.None)
      addNodeAndRelease(scene,avatfNode)
    elseif i==3 then
      avatfNode = KuruFloatingImageNode.createFromSampler(g_frameBufferSampler,1.0-0.30,0.9-topHeight-0.22*0.5625*3-2*marginY,0.230,0.22*0.5625,BlendMode.None)
      addNodeAndRelease(scene,avatfNode)
    elseif i==4 then
      avatfNode = KuruFloatingImageNode.createFromSampler(g_frameBufferSampler,1.0-0.30,0.9-topHeight-0.22*0.5625*4-3*marginY,0.230,0.22*0.5625,BlendMode.None)
      addNodeAndRelease(scene,avatfNode)
    elseif i==5 then
      avatfNode = KuruFloatingImageNode.createFromSampler(g_frameBufferSampler,1.0-0.30,0.9-topHeight-0.22*0.5625*5-4*marginY,0.230,0.22*0.5625,BlendMode.None)
      addNodeAndRelease(scene,avatfNode)
    else
      
    end
    avrtPhotos[i] = avatfNode
    avatfNode:setEnabled(false)
    local topNode = addNodeAndRelease(scene, KuruFloatingImageNode.create(BASE_DIRECTORY .. "b_up.png", -1.0, 1-topHeight, 2.0, topHeight, BlendMode.None))
    topNode:setEnabled(false)
    wxNodes[#wxNodes+1] = topNode
  middleHeight = 0.9
  bottomSampler = getStickerSampler("b_aabb",10)
  local bottomNode = KuruFloatingImageNode.createFromSampler(bottomSampler,-1.0,-1,2,middleHeight,BlendMode.None)
  wxNodes[#wxNodes+1] = bottomNode
  bottomNode:setEnabled(false)
  addNodeAndRelease(scene,bottomNode)
  end
end

function frameReady(scene, elapsedTime) --预览状态->RecordStart->拍摄状态->预览状态
  if RenderConfig.instance():isRenderModePreview() then --未点击拍摄按钮（无论视频或者皂片模式）
      if isPhotoTake==false then
        state = FrameBufferBindingState.create()
        g_material:getParameter("u_texture"):setSampler(resultNode:getSampler())
        g_frameBuffer:bindWithViewport(true)
        g_modelContext:draw()
        state:restore()
        for j=1,#originNodes do
          originNodes[j]:setEnabled(true)
        end
        for i=1,#wxNodes do
          wxNodes[i]:setEnabled(false)
        end
        for i=1,#avrtPhotos do
          avrtPhotos[i]:setEnabled(false)
        end 
      else
        if totalElapsedTime>0.0 then --防止上次录制没有捕获到结束操作导致状态没有reset(Preview模式下totalElapsedTime却大于0)
          totalElapsedTime=0.0
          isAniStart=false
          isPhotoTake=false
          g_sound:stop()
          return
        end
        for j=1,#originNodes do
            originNodes[j]:setEnabled(false)
        end
        for i=1,#wxNodes do
            wxNodes[i]:setEnabled(true)
        end
        eventExtension:postSimpleEventToApp("KaleSimpleEventVideoRecordStart", "")
      end
  elseif RenderConfig.instance():isRenderModeVideo() then --录制模式 （无论视频或者皂片模式）
      if isPhotoTake==false then --视频模式下isPhotoTake为false也可以进入录制模式
         return
      end
      if totalElapsedTime<=10.5 then --设置太大可能导致无法捕获结束状态而出错
        totalElapsedTime = totalElapsedTime+elapsedTime * 0.001*g_speed
        if isAniStart==false and (totalElapsedTime>0.4 or DeviceConfig.instance().platformType ~= DeviceConfigPlatformType.P_IOS) then
         -- DeviceConfig.instance().platformType == DeviceConfigPlatformType.P_IOS
            isAniStart=true
            g_sound:play(false)
            bottomSampler:stop()
            bottomSampler:setRepeatCount(1)
            bottomSampler:setFPS(10)
            bottomSampler:play()
        end
        playAni()
      else
        eventExtension:postSimpleEventToApp("KaleSimpleEventVideoRecordStop", "")
        totalElapsedTime=0.0
        isAniStart=false
        isPhotoTake=false
        g_sound:stop()
      end
  else
    
  end
end
function playAni()

  if bottomSampler:getFrameIndex()<=18 then
    for i=1,#avrtPhotos do
      avrtPhotos[i]:setEnabled(false)
    end --有时候会出现
    middleSampler:setTexture(messagetotolsamplers[6]:getTexture())
  elseif bottomSampler:getFrameIndex()<=43 then
    middleSampler:setTexture(messagetotolsamplers[1]:getTexture())
    avrtPhotos[1]:setEnabled(true)
  elseif bottomSampler:getFrameIndex()<=61 then
    middleSampler:setTexture(messagetotolsamplers[2]:getTexture())
    avrtPhotos[2]:setEnabled(true)
  elseif bottomSampler:getFrameIndex()<=77 then
    middleSampler:setTexture(messagetotolsamplers[3]:getTexture())
    avrtPhotos[3]:setEnabled(true)
  elseif bottomSampler:getFrameIndex()<=96 then
    middleSampler:setTexture(messagetotolsamplers[4]:getTexture())
    avrtPhotos[4]:setEnabled(true)
  else
    middleSampler:setTexture(messagetotolsamplers[5]:getTexture())
    avrtPhotos[5]:setEnabled(true)
  end
end

function onSimpleEvent(event)
  -- local e = KuruEventExtensionSimpleEventArgs.cast(event)
  -- local result = e:getArg()
  -- if e:getName() == "KaleSimpleEventVideoRecordStartResult" then
  --   if result == "RecordStarted" then
  --     print("RecordStarted")
  --   end
  -- end

  -- if e:getName() == "KaleSimpleEventVideoRecordStopResult" then
  --   if result == "RecordStopped" then
  --       print("RecordStopped")
  --   end
  -- end
end
function onTouchDown(event)
  isPhotoTake = true
end
function reset(scene)
  --解决android下无法暂停播放问题
 if DeviceConfig.instance().platformType ~= DeviceConfigPlatformType.P_IOS then
    totalElapsedTime=0.0
    isAniStart=false
    isPhotoTake=false
    g_sound:stop()
 end 
end
function finalize(scene)
  kuruTouch:getTouchDownEvent():removeEventHandler(onTouchDown)
  g_frameBuffer:release()
  g_frameBufferSampler:release()
  middleSampler:release()
  bottomSampler:release()
  eventExtension:getSimpleEvent():removeEventHandler(onSimpleEvent)
  for i=1,#messagetotolsamplers do
    messagetotolsamplers[i]:release()
  end
end

function addNodeAndRelease(scene, node)
  scene:addNode(node)
  node:release()
  return node
end

function createFullscreenQuadMode(sampler)
  local smesh = Mesh.createQuadFullscreen()
  local model = Model.create(smesh)
  smesh:release()

  g_material = Material.createWithShaderFile("res/shaders/passthrough.vert","res/shaders/passthrough.frag",nil)
  g_material:getParameter("u_worldViewProjectionMatrix"):setMatrix(Matrix:identity())
  g_material:getParameter("u_texture"):setSampler(sampler)
  model:setMaterial(g_material,-1)
  g_material:release()
  return model
end

function getCurrentShot(scene, bufferScale)
  local node = KuruSnapshotNode.create()
  node:setFrameBufferScale(bufferScale, bufferScale)
  scene:addNode(node)
  node:release()
  return node
end

function getStickerSampler(filepath,fps) --注意写成local形式会出问题
  local sp = KuruAnimationSampler.createFromPath(BASE_DIRECTORY..filepath,false,false)
  sp:setRepeatCount(1)
  sp:setFPS(10)
  return sp
end